/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package be.fedict.barth.signer;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.CRLException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509CRL;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.x509.CRLDistPoint;
import org.bouncycastle.asn1.x509.DistributionPoint;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils;
import org.bouncycastle.util.encoders.Hex;

/**
 *
 * @author hanssens_bart
 */
public class CRLGetter {
    
    private URL getCRLUrl(byte[] b) throws MalformedURLException, IOException {
        URL url = null;
        
        ASN1Primitive crlinfo = JcaX509ExtensionUtils.parseExtensionValue(b);
        CRLDistPoint point = CRLDistPoint.getInstance(crlinfo);
        for (DistributionPoint p : point.getDistributionPoints()) {
            GeneralNames name = (GeneralNames) p.getDistributionPoint().getName();
            for (GeneralName n : name.getNames()) {
                url = new URL(n.getName().toString());
            }
        }
        return url;
    }
    
    public X509CRL[] get(X509Certificate certificate, X509Certificate[] chain) throws IOException, CertificateException, CRLException {
        ArrayList<X509CRL> crls = new ArrayList<X509CRL>();
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        for (X509Certificate c : chain) {
            if (! c.equals(certificate)) {
                byte[] b = c.getExtensionValue(Extension.cRLDistributionPoints.getId());
                if (b != null) {
                    URL url = getCRLUrl(b);
                    HttpURLConnection conn = Util.Get(url);
                    InputStream is = conn.getInputStream();
                    X509CRL crl = (X509CRL) cf.generateCRL(is);
                    System.err.println(Hex.toHexString(crl.getEncoded()));
                    conn.disconnect();
                    crls.add(crl);
                }
            }
        }
        return crls.toArray(new X509CRL[0]);
    }
            
    public CRLGetter()  {
    }
}
